package cn.client.ui.view.main.mindfulness

import androidx.annotation.DrawableRes
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.paddingFromBaseline
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyHorizontalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import cn.client.R
import cn.client.data.remoteData.bean.MindfulnessMedia
import cn.client.data.remoteData.bean.PageSelect
import cn.client.data.remoteData.bean.PageSelectByUid
import cn.client.data.userStateManager
import cn.client.navigation.destinations.MindfulnessExercisePage
import coil.compose.AsyncImage
import kotlinx.coroutines.launch


// 首页推荐
@Composable
fun MindfulnessHomeRecommend(
    navController: NavController,
    viewModel: MindfulnessViewModel
) {

    val userIdState = userStateManager.userId.collectAsState(initial = -1)
    val userId = userIdState.value

    // 观察viewModel中的状态
    val recommendMindfulnessState =
        viewModel.recommendMindfulness.collectAsState(initial = emptyList())
    val recommendMindfulness = recommendMindfulnessState.value

    val mindfulnessMediaState = viewModel.mindfulnessMedia.collectAsState(initial = emptyList())
    val mindfulnessMedia = mindfulnessMediaState.value

    val mindfulnessGroupState = viewModel.mindfulnessGroup.collectAsState(initial = emptyList())
    val mindfulnessGroup = mindfulnessGroupState.value

    val pageSelect = PageSelect(pageNo = 1, pageSize = 10)
    val pageSelectByUid = PageSelectByUid(uid = userId, pageNo = 1, pageSize = 10)

    val coroutineScope = rememberCoroutineScope()

    coroutineScope.launch {
        viewModel.dispatch(MindfulnessViewModel.PageIntent.GetMindfulnessMediaList(pageSelect))
        viewModel.dispatch(MindfulnessViewModel.PageIntent.GetRecommendMindfulness(pageSelectByUid))
        viewModel.dispatch(MindfulnessViewModel.PageIntent.GetMindfulnessGroupList(pageSelect))
    }



    Column(
        modifier = Modifier
            .fillMaxSize()
            .verticalScroll(rememberScrollState()) // 设置滚动
    ) {

        Spacer(Modifier.height(16.dp))

        HomeSection("推荐") {
            LazyRow(
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                contentPadding = PaddingValues(horizontal = 10.dp),
                modifier = Modifier
            ) {
                items(recommendMindfulness) { media ->
                    RecommendMediaElement(
                        media = media,
                        onClickMindfulnessMedia = {
                            navController.navigate(MindfulnessExercisePage.route + "/${media.id}")
                        })
                }
            }
        }

        HomeSection("正念练习") {
            LazyRow(
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                contentPadding = PaddingValues(horizontal = 10.dp),
                modifier = Modifier
            ) {
                items(mindfulnessMedia) { media ->
                    MindfulnessMediaElement(
                        media = media,
                        onClickMindfulnessMedia = {
                            navController.navigate(MindfulnessExercisePage.route + "/${media.id}")
                        }
                    )
                }
            }
        }

        HomeSection("团体") {
            LazyHorizontalGrid(
                rows = GridCells.Fixed(2),
                contentPadding = PaddingValues(horizontal = 10.dp),
                horizontalArrangement = Arrangement.spacedBy(16.dp),
                verticalArrangement = Arrangement.spacedBy(16.dp),
                modifier = Modifier.height(168.dp),
            ) {
                items(mindfulnessGroup) { item ->
                    MindfulnessGroupCard(R.drawable.ic_peoples, item.groupName, Modifier.height(80.dp))
                }
            }
        }
        Spacer(Modifier.height(16.dp))
    }
}


// 正念媒体item
@Composable
fun MindfulnessMediaElement(
    media: MindfulnessMedia,
    onClickMindfulnessMedia: () -> Unit,
    modifier: Modifier = Modifier
) {

    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = modifier.width(90.dp)
    ) {
        AsyncImage(
            model = media.imgUrl,
            contentDescription = null,
            contentScale = ContentScale.Crop,
            modifier = Modifier
                .size(88.dp)
                .clip(CircleShape)
                .clickable {
                    onClickMindfulnessMedia()
                }
        )
        Text(
            text = media.mediaName,
            modifier = Modifier.paddingFromBaseline(top = 24.dp, bottom = 8.dp),
            style = MaterialTheme.typography.bodyMedium,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
    }
}
@Composable
fun RecommendMediaElement(
    media: MindfulnessMedia,
    onClickMindfulnessMedia: () -> Unit,
    modifier: Modifier = Modifier
) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = modifier.width(90.dp)
    ) {
        AsyncImage(
            model = media.imgUrl,
            contentDescription = null,
            contentScale = ContentScale.Crop,
            modifier = Modifier
                .size(88.dp)
                .clip(CircleShape)
                .clickable {
                    onClickMindfulnessMedia()
                }
        )
        Text(
            text = media.mediaName,
            modifier = Modifier.paddingFromBaseline(top = 24.dp, bottom = 8.dp),
            style = MaterialTheme.typography.bodyMedium,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
        // Text组件，当文本超过容器宽度时显示省略号
    }
}
// 正念团体item
@Composable
fun MindfulnessGroupCard(
    @DrawableRes drawable: Int,
    text: String,
    modifier: Modifier = Modifier
) {
    Surface(
        shape = MaterialTheme.shapes.medium,
        color = MaterialTheme.colorScheme.surfaceVariant,
        modifier = modifier
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier.width(255.dp)
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.Center,
                modifier = Modifier.size(80.dp)
            ) {
                Image(
                    painter = painterResource(drawable),
                    contentDescription = null,
                    contentScale = ContentScale.Crop,
                    modifier = Modifier.size(40.dp)
                )
            }
            Text(
                text = text,
                style = MaterialTheme.typography.titleMedium,
                modifier = Modifier.padding(horizontal = 16.dp)
            )
        }
    }
}


// 槽位
@Composable
fun HomeSection(
    title: String,
    modifier: Modifier = Modifier,
    content: @Composable () -> Unit
) {
    Column(modifier) {
        Text(
            text = title,
            style = MaterialTheme.typography.titleMedium,
            modifier = Modifier
                .paddingFromBaseline(top = 40.dp, bottom = 16.dp)
                .padding(horizontal = 16.dp)
        )
        content()
    }
}